import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Login from "../views/Login/Login.vue";
import { userInfoAPI } from "@/http/api";
import { useUserKey } from "@/store/user";
import { ElMessage } from "element-plus";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/",
    redirect: "index",
    component: () => import("../views/Home/index.vue"),
    children: [
      {
        path: "index",
        component: () => import("../views/Index/index.vue"),
      },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token");
  const userStore = useUserKey();
  if (userStore.menus.length === 0 && token) {
    userInfoAPI().then((res) => {
      // console.log(res);
      if (res.code === 200) {
        userStore.menus = res.data.menus;
        userStore.username = res.data.username;
        // 生成当前用户可以访问的路由
        // 现在当前用户能访问的所有路由在pinia里面
        userStore.routes.forEach((p) => {
          const route: RouteRecordRaw = {
            path: "/" + p.name,
            name: p.name,
            component: () => import("../views/Home/index.vue"),
            meta: {
              // 在meta里面把对应的中文名字存好，然后路由中获取生成面包屑
              title: p.title,
            },
            children: p.children?.map((item) => ({
              path: item.name,
              name: item.name,
              meta: {
                // 在meta里面把对应的中文名字存好，然后路由中获取生成面包屑
                title: item.title,
              },
              component: () => import(`../views/${p.name}/${item.name}.vue`),
            })),
          };
          // 当访问一级路由时，默认跳转到第一个子路由
          if (p.children[0]) {
            route.redirect = `/${p.name}/${p.children[0].name}`;
          }
          router.addRoute(route);
        });
        next(to.fullPath);
      }
    });
  } else if (!token && to.path !== "/login") {
    ElMessage.error("请先登录");
    next("/login");
  } else if (token && userStore.menus.length !== 0 && to.path === "/login") {
    next(from.fullPath);
    ElMessage.warning("请退出登录，再重新登录");
  } else {
    next();
  }
  // console.log(router.getRoutes());
});

export default router;
